//
//  SchoolRecordBar.m
//  Learn
//
//  Created by zyl_macbookpro on 2024/4/7.
//  Copyright © 2024 迟建国. All rights reserved.
//

#import "SchoolRecordBar.h"
#import "SchoolRecordBarColor.h"
@implementation SchoolRecordBar

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _chartLine = [CAShapeLayer layer];
        _chartLine.lineCap = kCALineCapSquare;
        _chartLine.fillColor = [UIColor whiteColor].CGColor;
        _chartLine.lineWidth = self.frame.size.width;
        _chartLine.strokeEnd = 0.0;
        [self.layer addSublayer:_chartLine];
        self.clipsToBounds = YES;
        self.layer.cornerRadius = 2.0;
    }
    return self;
}

-(void)setGradePercent:(float)gradePercent
{
    if (gradePercent==0)
    return;
    
    _gradePercent = gradePercent;
    UIBezierPath *progressline = [UIBezierPath bezierPath];
    
    [progressline moveToPoint:CGPointMake(self.frame.size.width/2.0, self.frame.size.height+30)];
    [progressline addLineToPoint:CGPointMake(self.frame.size.width/2.0, (1 - gradePercent) * self.frame.size.height+15)];
    [progressline setLineWidth:1.0];
    [progressline setLineCapStyle:kCGLineCapSquare];
    _chartLine.path = progressline.CGPath;
    _chartLine.strokeColor = _barColor.CGColor ?: [SchoolRecordBarColor green].CGColor;
    
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 1.5;
    pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pathAnimation.fromValue = @0.0;
    pathAnimation.toValue = @1.0;
    pathAnimation.autoreverses = NO;
    [_chartLine addAnimation:pathAnimation forKey:@"strokeEndAnimation"];
    
    _chartLine.strokeEnd = 2.0;
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, (1 - gradePercent) * self.frame.size.height + 15 - 12 - 10, self.width, 12)];
    lab.text = self.number;
    lab.textColor = self.barColor;
    lab.font = RFontWithSize(12);
    [lab sizeToFit];
    [self addSubview:lab];
    
}
- (void)setNumber:(NSString *)number
{
    _number = number;
    
}
- (void)drawRect:(CGRect)rect
{
    //Draw BG
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
    CGContextFillRect(context, rect);
}

@end
